import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken, getToken, removeToken } from "@/utils/token.js";
import { loginApi, userInfoApi } from "@/apis/user.js";

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken(), // 用户登录凭证
    userInfo: {}, // 用户信息
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      _setToken(action.payload); // 将token存储到本地
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
  },
});

const saveToken = (loginForm) => {
  return async (dispatch) => {
    const res = await loginApi(loginForm);
    console.log("保存token的接口返回值", res);
    // 保存token到redux
    dispatch(setToken(res.token));
  };
};

const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await userInfoApi();
    console.log("根据token获取用户信息的接口返回值", res);
    // 保存token到redux
    dispatch(setUserInfo(res));
  };
};

const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

const userReducer = userStore.reducer;

export { saveToken, setToken, fetchUserInfo, clearUserInfo };
export default userReducer;
